from django.core.checks import messages
from django.shortcuts import get_object_or_404, render,redirect
from wms.models import Warehouse
from .forms import WarehouseForm
from django.core.paginator import Paginator
# from rest_framework.viewsets import ViewSet, ModelViewSet
# from wms.serializers import WarehouseInfoModelSerializer
# Create your views here.
def index(request):
    return render(request,'index.html')

def warehouses_list(request):
    warehouses_list=Warehouse.objects.all()
    Pageor=Paginator(warehouses_list,10)
    page_number=request.GET.get('page')
    page_obj=Pageor.get_page(page_number)
    print('page_obj',page_obj)
    return render(request,
                  'warehouse_list.html',{'page_obj':page_obj})

# class wh_Maintenance(ModelViewSet):
    # Warehouses=Warehouse.objects.all()
    # serializer_class = WarehouseInfoModelSerializer

def warehouse_create(request):
    if request.method == 'POST':
        form = WarehouseForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('warehouses_list')
    else:
        form = WarehouseForm()
    return render(request, 'warehouses_form.html', {'form': form})

def warehouse_edit(request,pk):
    Whouse=get_object_or_404(Warehouse,pk=pk)
        
    if request.method == 'POST':
        form = WarehouseForm(request.POST, instance=Whouse)
        if form.is_valid():
            form.save()
            return redirect('warehouses_list')
    else:
        form=WarehouseForm(instance=Whouse)
    return render(request, 'warehouses_form.html', {'form': form})

def warehouse_delete(request,pk):
        Whouse=get_object_or_404(Warehouse,pk=pk)
        if request.method == 'POST':
            try:
                Whouse.delete()
                messages.Error(request,'删除成功！')
                return redirect('warehouses_list')

            except Exception as e:
                messages.Error(request,f'删除仓库时出错:{e}')
        return render(request, 'warehouses_confirm_delete.html', {'warehouse':Whouse})

